//
//  ZFNormalViewController.m
//  ZFPlayer
//
//  Created by 紫枫 on 2018/3/21.
//  Copyright © 2018年 紫枫. All rights reserved.
//
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "VideoPlayerViewController.h"
#import "ReportViewController.h"
#import "ExercisesAnswerResultViewController.h"
#import "ExercisesPageViewController.h"
#import "ZFLessonControl.h"
#import "XHVideoRateView.h"
#import "XHVideoMoreView.h"

#import "XHVideoFeedbackView.h"
#import "VideoPlayFinishView.h"
#import "VideoNextPlayView.h"
#import "VideoloadingModel.h"
#import "LessonUseageModel.h"
#import "WHToast.h"

#import "VideoShareView.h"

@interface VideoPlayerViewController ()
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFLessonControl *controlView;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) UIButton *changeBtn;
@property (nonatomic, strong) UIButton *nextBtn;
@property (nonatomic, strong) NSArray <NSURL *>*assetURLs;

@property (nonatomic,strong)dispatch_queue_t quene;
//@property (nonatomic,strong)dispatch_source_t timer;

@property (nonatomic,strong)NSTimer *useage_timer;


@property (nonatomic,strong)LessonPageItemModel *currentModel;

@property (nonatomic,assign)BOOL isAnswer;

@property (nonatomic,assign)CGFloat currentBrightness;

/// 播放状态
@property (nonatomic,strong)NSNumber *playStatus;

@property (nonatomic,assign)BOOL isFinish;

@end

@implementation VideoPlayerViewController



- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    self.isHideNavBar = YES;
    
    self.currentModel = self.items.firstObject;
   
    [self setupPlayer];
    
    [self registNote];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.player.viewControllerDisappear = NO;

    [self.player enterFullScreen:YES animated:NO];
    
    if (self.playStatus.intValue != 2) {
        [self.player.currentPlayerManager play];
    }else{
        [self.player.currentPlayerManager pause];
    }
    
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    // 开始定时器
     self.useage_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshUseageTime) userInfo:nil repeats:YES];
          [[NSRunLoop currentRunLoop] addTimer:self.useage_timer forMode:NSRunLoopCommonModes];

}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    // 销毁定时器记录学习时间
    [self.useage_timer invalidate];
    
    self.useage_timer = nil;
    
    self.player.viewControllerDisappear = YES;
        
    ((AppDelegate *)([UIApplication sharedApplication].delegate)).allowOrentitaionRotation = NO;


}

#pragma mark - 外部停止播放
- (void)stopVideoPlayer{
    [self updatePlayerStatus];
    [self.controlView.player.currentPlayerManager pause];
    [self.player enterFullScreen:NO animated:NO];
}
#pragma mark - 销毁新手引导
-(void)removeAllHelpView{
    [self.controlView.landScapeControlView removeAllCoverView];
}

#pragma mark - 处理通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCardStatus:) name:@"updateAboutQuestionSource" object:nil];
}
- (void)updateCardStatus:(NSNotification *)note{
    // 本地默认已经答题
    self.currentModel.isAnswerd = [note.userInfo[@"isFinish"]boolValue];
}
#pragma mark - 设置播放器
- (void)setupPlayer {
    
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    
    [self.controlView.landScapeControlView bindModel:self.lessonModel];
    /// 播放器相关
    self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.view];
    self.player.controlView = self.controlView;
    self.player.allowOrentitaionRotation = NO;
    self.player.WWANAutoPlay = YES;
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        ((AppDelegate *)([UIApplication sharedApplication].delegate)).allowOrentitaionRotation = isFullScreen;

    };
    // 返回按钮事件
    __weak typeof(self)weakSelf = self;
    /// 播放完成
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        
        __strong typeof(weakSelf)strongSelf = weakSelf;
        
        if (strongSelf.isFinish) {
            return;
        }
        
        strongSelf.isFinish = YES;
        
        // 保存视频进度
        NSInteger index = strongSelf.player.currentPlayIndex;
        LessonPageItemModel *item = strongSelf.items[index];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"lessonId"] = item.id;
        param[@"videoPlayedTime"] = @(10000);
        param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserVideoLog];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveUserVideoLog) parames:param success:^(id responseObj) {

        } failure:^(id error) {

        }];
        // 防止往回拖拽
        weakSelf.controlView.bottomPgrogress.userInteractionEnabled = NO;
        // 删除播放进度记录，播放完毕
        RLMResults *results = [[VideoloadingModel allObjects] objectsWhere:[NSString stringWithFormat:@"lessonId == %d and userId == %d",strongSelf.self.currentModel.id.intValue,[RPAppManager getCustomerId].intValue]];
        if (results.count > 0) {
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [[RLMRealm defaultRealm] deleteObject:results.firstObject];
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }

        
        
        NSString *confirmTitle = @"写课后练习";
        
        if (self.lessonModel.paper == nil) {
            confirmTitle = @"";
        }
        
        VideoPlayFinishView *finishView = [[VideoPlayFinishView alloc]initWithTitle:@"恭喜你已学完本课程" message:@"离梦想又近了一步哦，请继续加油！" confirmTitle:confirmTitle cancelTitle:@"再次播放" confirmAciton:^{
            [strongSelf addUserPlan];
            strongSelf.isFinish = NO;
        } cancelAction:^{
            strongSelf.isFinish = NO;
            // 判断是否加入学习计划
            if (strongSelf.currentModel.isSeleted) {
                [strongSelf.player.currentPlayerManager replay];
            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"将课程加入学习计划，就不怕课程丢失啦～" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [alertController dismissViewControllerAnimated:YES completion:nil];
                    [strongSelf.player.currentPlayerManager replay];
                    [strongSelf addUserPlanList];
                }];

                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不用，直接看" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [alertController dismissViewControllerAnimated:YES completion:nil];
                        [strongSelf.player.currentPlayerManager replay];
                }];
                [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
                [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
                         //往alertViewController上添加alertAction
                [alertController addAction:confirmAction];
                [alertController addAction:cancelAction];
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
            }
        }];
        [finishView show];
        [strongSelf.player.currentPlayerManager pause];
    };
//
    self.player.assetURLs = self.assetURLs;
    [self.player playTheIndex:0];
    
    RLMResults *results = [[VideoloadingModel allObjects] objectsWhere:[NSString stringWithFormat:@"lessonId == %d and userId == %d",self.currentModel.id.intValue,[RPAppManager getCustomerId].intValue]];
    if (results.count > 0) {
        VideoloadingModel * model = results.firstObject;
        [self.player seekToTime:model.currentTime completionHandler:^(BOOL finished) {

        }];
    }

    if (self.currentModel.isSeleted) {
        [self.controlView.landScapeControlView updateAddBtnStatus];
    }
    
    self.controlView.landScapeControlView.backBtnClickCallback = ^{
        
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.player.currentPlayerManager pause];
        VideoPlayFinishView *finishView = [[VideoPlayFinishView alloc]initWithTitle:@"确定退出吗？" message:@"学如逆水行舟，不进则退" confirmTitle:@"继续学" cancelTitle:@"是的，退出" confirmAciton:^{
            [strongSelf.player.currentPlayerManager play];
        } cancelAction:^{
            if (strongSelf.player.orientationObserver.supportInterfaceOrientation & ZFInterfaceOrientationMaskPortrait) {
                [strongSelf.player enterFullScreen:NO animated:NO];
                if (strongSelf.updateVideoProgress) {
                    strongSelf.updateVideoProgress(strongSelf.player.currentTime, strongSelf.player.totalTime);
                }

                if (strongSelf.updateVideoProgressWithCurentModel) {
                    strongSelf.updateVideoProgressWithCurentModel(strongSelf.player.currentTime, strongSelf.player.totalTime,strongSelf.currentModel);
                }
                // 保存当前的视频时间
                // 首选判断数据库中是否存在视频
                RLMRealm *realm = [RLMRealm defaultRealm];
                RLMResults *results = [[VideoloadingModel allObjects] objectsWhere:[NSString stringWithFormat:@"lessonId == %d and userId == %d",strongSelf.currentModel.id.intValue,[RPAppManager getCustomerId].intValue]];
                if (results.count > 0) {
                    [realm beginWriteTransaction];
                    VideoloadingModel * model = results.firstObject;
                    model.currentTime = strongSelf.player.currentTime;
                    [realm commitWriteTransaction];
                    
                    [MobClick event:@"lesson_play_duration" durations:model.currentTime];
                    
                }else{
                    VideoloadingModel *newModel = [VideoloadingModel new];
                    newModel.userId = [RPAppManager getCustomerId].intValue;
                    newModel.currentTime = strongSelf.player.currentTime;
                    newModel.videoId = strongSelf.currentModel.videoId.intValue;
                    newModel.lessonId = strongSelf.currentModel.id.intValue;
                    [realm transactionWithBlock:^{
                        [realm addOrUpdateObject:newModel];
                    }];
                    [MobClick event:@"lesson_play_duration" durations:newModel.currentTime];
                }
                
                [strongSelf dismissViewControllerAnimated:YES completion:nil];
            
            }
        }];
        [finishView show];
    };
    
 
    self.controlView.landScapeControlView.rateBtnClickCallback = ^{
        
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.player.currentPlayerManager pause];
        XHVideoRateView *rateView = [[XHVideoRateView alloc]initWithCompleteBlock:^(NSInteger index) {

            if (index == 0) {
                strongSelf.controlView.landScapeControlView.player.currentPlayerManager.rate = 1.5;
                [MobClick event:@"video_rate_1_5"];
            }
            if (index == 1) {
                strongSelf.controlView.landScapeControlView.player.currentPlayerManager.rate = 1.25;
                [MobClick event:@"video_rate_1_2_5"];
            }
            if (index == 2) {
                strongSelf.controlView.landScapeControlView.player.currentPlayerManager.rate = 1.0;
            }
            if (index == 3) {
                strongSelf.controlView.landScapeControlView.player.currentPlayerManager.rate = 0.5;
                [MobClick event:@"video_rate_0_5"];
            }
            [strongSelf.player.currentPlayerManager play];
            [strongSelf.controlView.landScapeControlView updateRate:strongSelf.controlView.landScapeControlView.player.currentPlayerManager.rate];
        }];
        [rateView show];
    };

    self.controlView.landScapeControlView.darkBtnClickCallback = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [MobClick event:@"video_dark_brightness"];
        
        if (strongSelf.controlView.landScapeControlView.isSaveStatus) {
            strongSelf.currentBrightness = strongSelf.player.brightness;
            strongSelf.controlView.player.brightness = 0.2;
            [strongSelf.controlView.volumeBrightnessView updateProgress:0.2 withVolumeBrightnessType:ZFVolumeBrightnessTypeumeBrightness];
        }else{
            strongSelf.controlView.player.brightness = strongSelf.currentBrightness;
            [strongSelf.controlView.volumeBrightnessView updateProgress:strongSelf.currentBrightness withVolumeBrightnessType:ZFVolumeBrightnessTypeumeBrightness];
        }
        

    };
//
    self.controlView.landScapeControlView.moreBtnClickCallback = ^{
        [MobClick event:@"video_feedback_click"];
        __strong typeof(weakSelf)strongSelf = weakSelf;
        XHVideoMoreView *moreView = [[XHVideoMoreView alloc]initWithCompleteBlock:^(NSInteger index) {
            [strongSelf updatePlayerStatus];
            [strongSelf.controlView.player.currentPlayerManager pause];
            if (index == 1) {
                if (![RPAppManager isLogin]) {
                    [strongSelf.player enterFullScreen:NO animated:NO];
                    [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":strongSelf.navigationController} completion:nil];
                }else{
                    XHVideoFeedbackView *feedbackView = [[XHVideoFeedbackView alloc]initWithCompleteBlock:^(NSString * _Nonnull content) {
                        if (content.length > 0) {
                            NSMutableDictionary *param = [NSMutableDictionary dictionary];
                            param[@"content"] = content;
                            param[@"md5"] = [RPAppManager md5StrWithApi:AddFeedback];
                            param[@"userId"] = [RPAppManager getCustomerId];
                            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddFeedback) parames:param success:^(id responseObj) {
                                [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"感谢您的反馈，我们会努力进步的" duration:2 finishHandler:nil];
                                if (strongSelf.playStatus.intValue != 2) {
                                    [strongSelf.player.currentPlayerManager play];
                                }else{
                                    [strongSelf.player.currentPlayerManager pause];
                                }
                            } failure:^(id error) {
                                if (strongSelf.playStatus.intValue != 2) {
                                    [strongSelf.player.currentPlayerManager play];
                                }else{
                                    [strongSelf.player.currentPlayerManager pause];
                                }
                             }];
                        }else{
                            if (strongSelf.playStatus.intValue != 2) {
                                [strongSelf.player.currentPlayerManager play];
                            }else{
                                [strongSelf.player.currentPlayerManager pause];
                            }
                        }
                    }];
                    [feedbackView show];
                }
            }
            if (index == 2) {
                // 切换至横屏跳转
                [strongSelf.player enterFullScreen:NO animated:NO];
                if (![RPAppManager isLogin]) {
                    [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":strongSelf.navigationController} completion:nil];
                }else{
                    ReportViewController *reportVC = [[ReportViewController alloc]initWithReportType:XHREPORTVIDEO reportId:strongSelf.currentModel.videoId];
                    [strongSelf.navigationController pushViewController:reportVC animated:YES];
                    reportVC.done = ^{
                        [strongSelf.player.currentPlayerManager play];
                    };
                }

            }
        }];
        [moreView show];
    };
//
    self.controlView.landScapeControlView.shareBtnClickCallback = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.player.currentPlayerManager pause];
    };
    self.controlView.landScapeControlView.afterBtnClickCallback = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        
        [MobClick event:@"video_exam_click"];
        
        [strongSelf updatePlayerStatus];
        
        [strongSelf.player.currentPlayerManager pause];
        
        [strongSelf addUserPlan];
    };

    self.controlView.landScapeControlView.adddBtnClickCallback = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [MobClick event:@"video_add_plan_click"];
        [strongSelf addUserPlanList];
    };

    self.controlView.landScapeControlView.hideHelpViewClickCallback = ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.controlView.autoHiddenTimeInterval = 5.0f;
        [strongSelf.controlView autoFadeOutControlView];
    };
//
    self.controlView.landScapeControlView.shareBtnClickCallback = ^{
        
        __strong typeof(weakSelf)strongSelf = weakSelf;
       
        [strongSelf updatePlayerStatus];
        
        [strongSelf.player.currentPlayerManager pause];
        
        VideoShareView *shareView = [[VideoShareView alloc]initWithCompleteBlock:^(XHShareViewPlatformType platformType) {
            
            UMSocialPlatformType type = UMSocialPlatformType_UnKnown;
            switch (platformType) {
                case XHShareViewPlatformTypeWeChatSession:
                    type = UMSocialPlatformType_WechatSession;
                    break;
                case XHShareViewPlatformTypeWeChatMoments:
                    type = UMSocialPlatformType_WechatTimeLine;
                    break;
                case XHShareViewPlatformTypeQQ:
                    type = UMSocialPlatformType_QQ;
                    break;
                    
                case XHShareViewPlatformTypeQQZone:
                    type = UMSocialPlatformType_Qzone;
                    break;
                
                case XHShareViewPlatformTypeQQWeibo:
                    type = UMSocialPlatformType_Sina;
                    break;
                default:
                    break;
            }
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
            NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
            UIImage *shareImage= [UIImage imageNamed:icon];
            //创建网页内容对象
            
            
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:strongSelf.currentModel.title descr:strongSelf.currentModel.intro.length == 0?@"赋能万千莘莘学子":strongSelf.currentModel.intro thumImage:shareImage];
            //设置网页地址
            shareObject.webpageUrl = [NSString stringWithFormat:@"%@lesson/lesson/%@",HtmlUrl,strongSelf.currentModel.id];
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:strongSelf completion:^(id data, NSError *error) {
                if (error) {
                    UMSocialLogInfo(@"************Share fail with error %@*********",error);
                }else{
                    if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                        UMSocialShareResponse *resp = data;
                        //分享结果消息
                        UMSocialLogInfo(@"response message is %@",resp.message);
                        //第三方原始返回的数据
                        UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                        
                        if (strongSelf.playStatus.intValue != 2) {
                            [strongSelf.player.currentPlayerManager play];
                        }else{
                            [strongSelf.player.currentPlayerManager pause];
                        }
                    }else{
                        UMSocialLogInfo(@"response data is %@",data);
                    }
                    [MobClick event:@"lesson_detail_share"];
                    
                    [MobClick event:@"video_share_lesson"];
                    
                    [MobClick event:@"lesson_share_total" attributes:@{@"page":@"player"}];
                    
                }
            }];
        }];
        [shareView show];
    };
    
    [self.controlView showTitle:self.currentModel.title coverURLString:nil fullScreenMode:ZFFullScreenModeAutomatic];
    

}


- (void)saveVideoLog{
    
    CGFloat currentTime = self.player.currentTime;
    CGFloat totalTime = self.player.totalTime;
    
    CGFloat rounded_up2 = currentTime / totalTime;
    int value = (int)(floorf(rounded_up2 * 100 * 100));
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = self.currentModel.id;
    param[@"videoPlayedTime"] = @(value);
    param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserVideoLog];
    
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveUserVideoLog) parames:param success:^(id responseObj) {
    
    } failure:^(id error) {
    
    }];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (ZFLessonControl *)controlView {
    if (!_controlView) {
        _controlView = [ZFLessonControl new];
        _controlView.fastViewAnimated = YES;
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstPlayVideo"]boolValue]) {
            _controlView.autoHiddenTimeInterval = 5;
        }else{
            _controlView.autoHiddenTimeInterval = 9999;
        }
        _controlView.autoFadeTimeInterval = 0.5;
        _controlView.prepareShowLoading = YES;
        _controlView.prepareShowControlView = YES;
        _controlView.fullScreenMode = ZFFullScreenModeLandscape;
    }
    return _controlView;
}




- (NSArray<NSURL *> *)assetURLs {
    if (!_assetURLs) {
        __block NSMutableArray *urls = [NSMutableArray array];
        [self.items enumerateObjectsUsingBlock:^(LessonPageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [urls addObject:[NSURL URLWithString:obj.videoUrl]];
        }];
        _assetURLs = urls;
    }
    return _assetURLs;
}
- (void)addUserPlan{
    
    self.isAnswer = NO;
    
    if (!self.currentModel.isSeleted) {
        __weak typeof(self)weakSelf = self;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"将课程加入学习计划，就不怕课程丢失啦～" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            weakSelf.isAnswer = YES;
            [weakSelf addUserPlanList];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不用，直接练" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
            [weakSelf startExerceserAnswer];
        }];
        [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
        [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
       //往alertViewController上添加alertAction
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    }else{
        [self startExerceserAnswer];
    }
}

- (void)startExerceserAnswer{
    __weak typeof(self)weakSelf = self;
    if (![RPAppManager isLogin]) {
        
        [self.player enterFullScreen:NO animated:NO completion:^{
            [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
        }];
        return;
    }
    
    [self.player enterFullScreen:NO animated:NO completion:^{
        BOOL isFinish = NO;
        if (weakSelf.player.currentTime == weakSelf.player.totalTime && weakSelf.player.totalTime > 0) {
            isFinish = YES;
        }
        
        if (self.currentModel.isAnswerd) {
            ExercisesAnswerResultViewController *resultVC = [[ExercisesAnswerResultViewController alloc]init];
            resultVC.lessonId = weakSelf.currentModel.id.stringValue;
            resultVC.isFinishVideo = isFinish;
            [weakSelf.navigationController pushViewController:resultVC animated:YES];
        }else{
            ExercisesPageViewController *pageVC = [[ExercisesPageViewController alloc]initWithLessonId:weakSelf.currentModel.id paperId:weakSelf.currentModel.paperId];
            pageVC.isVideoFinish = isFinish;
            [weakSelf.navigationController pushViewController:pageVC animated:YES];
        }
        
    }];
    

    [self saveVideoLog];

}

- (void)updatePlayerStatus{
    if (self.player.currentPlayerManager.isPlaying) {
        self.playStatus = @(1);
    }else{
        self.playStatus = @(2);
    }
}

#pragma mark - 请求接口
- (void)addUserPlanList{
    
    if (![RPAppManager isLogin]) {
        __weak typeof(self)weakSelf = self;
        [self.player enterFullScreen:NO animated:NO completion:^{
            [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":weakSelf.navigationController} completion:nil];
        }];
        return;
    }
    
    if (!self.currentModel.isSeleted) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"lessonId"] = self.currentModel.id;
        param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
            
            NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
            [arr addObject:self.currentModel.id];
            [RPAppManager saveUserPlanIdsWithPlans:arr];
            
            self.currentModel.isSeleted = YES;
            // 取出对应的
            //改变按钮状态
            [self.controlView.landScapeControlView updateAddBtnStatus];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStudyList" object:nil];
            
  
            if (self.updatePlanStatus) {
                self.updatePlanStatus();
            }
            if (self.isAnswer) {
                [self startExerceserAnswer];
            }
            
        } failure:^(NSError *error) {
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }
}
//#pragma mark - showNextView
//- (void)showNextView{
//    __block NSInteger second = 3;
//    self.quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,self.quene);
//    dispatch_source_set_timer( self.timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
//    dispatch_source_set_event_handler( self.timer, ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (second == 0) {
//
//                dispatch_cancel(self.timer);
//                __weak typeof(self)weakSelf = self;
//                VideoNextPlayView *nextView = [[VideoNextPlayView alloc]initWithConfirmAciton:^{
//                    __strong typeof(weakSelf)strongSelf = weakSelf;
//                    [strongSelf addUserPlan];
//                } cancelAction:^{
//                    __strong typeof(weakSelf)strongSelf = weakSelf;
//                    [strongSelf.player.currentPlayerManager replay];
//                } nextAction:^{
//                    __strong typeof(weakSelf)strongSelf = weakSelf;
//                    [strongSelf.player playTheNext];
//                    strongSelf.currentModel = strongSelf.items[strongSelf.player.currentPlayIndex];
//                    [strongSelf.controlView showTitle:self.currentModel.title coverURLString:nil fullScreenMode:ZFFullScreenModeAutomatic];
//                }];
//                [nextView show];
//
//            } else {
//                second--;
//            }
//        });
//    });
//    dispatch_resume(self.timer);
//}

#pragma mark - 更新用户学习时间
- (void)refreshUseageTime{
    LessonUseageModel * model = [LessonUseageModel getUseage];
    NSInteger currentTime = model.currentTodayTime.intValue;
    currentTime+=1000;
    model.currentTodayTime = @(currentTime);
    [model save];
}
- (void)dealloc{
    
}
@end
